package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.entity.Patient;
import com.mapper.PatientMapper;
import com.service.PatientService;
import com.untils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class PatientServiceImpl extends ServiceImpl<PatientMapper, Patient> implements PatientService {
    @Autowired
    PatientMapper patientMapper;

    @Override
    public String login_patient(Patient patient){
        System.out.println("进入login_patient");
        List<Patient> selectedList = list(new LambdaQueryWrapper<Patient>()
                .eq(Patient::getPatientID, patient.getPatientID()));
        if (selectedList.isEmpty()) {
            throw new RuntimeException("账号不存在哦 请先注册吧~");
        }
        Patient selected = selectedList.get(0);
        String encodedPassword = selected.getPSW();
        // 判断密码是否正确
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean result = passwordEncoder.matches(patient.getPSW(), encodedPassword);
        System.out.println("经过密码判断，结果：" + result);
        if (!result) {
            throw new RuntimeException("账号或密码有误 请再检查检查~");
        }
        // 生成令牌
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("patientID", selected.getPatientID());
        map.put("psw", selected.getPSW());
        System.out.println("返回令牌，令牌为：" + JwtUtil.generateToken(map));
        return JwtUtil.generateToken(map);
    }

    @Override
    public String register_patient(Patient patient) {
        // 密码加密
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(patient.getPSW());
        patient.setPSW(encodedPassword);
        patientMapper.insert(patient);
        return "Success";
    }

    @Override
    public String hasRegister(String PatientID) {
        if (patientMapper.selectList(new LambdaQueryWrapper<Patient>()
                .eq(Patient::getPatientID, PatientID)).isEmpty()) {
            System.out.println("返回Success");
            return "Success";
        }
        System.out.println("返回Error");
        return "Error";
    }
}
